package com.zzt.pagehelp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.zzt.pagehelp.databinding.ActivityMainBinding
import com.zzt.pagehelp.util.*
import android.R
import android.app.ProgressDialog
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.zzt.pagehelp.util2.IPageSize
import kotlinx.coroutines.launch


class MainActivity : AppCompatActivity() {
    val TAG = MainActivity::class.java.simpleName
    lateinit var binding: ActivityMainBinding

    lateinit var pageHelper: PageHelper<String>

    var progressDialog: ProgressDialog? = null

    var tiXingAdapter: TiXingAdapter<String, BaseViewHolder>? = null

    // 分页
    private var mPageSize: IPageSize? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
//        initView1()
        initView2()
    }

    private fun initView() {
        binding.rvDataList?.apply {
            tiXingAdapter = TiXingAdapter<String, BaseViewHolder>()
            tiXingAdapter?.data = mutableListOf();//requestList(0, 20)
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = tiXingAdapter
        }
    }

    private fun initView2() {
        mPageSize = object : IPageSize(1, 20) {
            override fun load(pageIndex: Int, pageSize: Int) {
                Log.e(TAG, "查看当前加载数据  pageIndex:$pageIndex pageSize:$pageSize ")
                val requestList = requestList(page = pageIndex, pageSize = pageSize)
                if (requestList.isNotEmpty()) {
                    if (mPageSize?.isFirstPage == true) {
                        tiXingAdapter?.setList(requestList)
                    } else {
                        tiXingAdapter?.addData(requestList)
                    }
                    mPageSize?.finishLoad(true)
                } else {
                    mPageSize?.finishLoad(false)
                }
                binding.srlRefreshLayout.finishRefresh()
                binding.srlRefreshLayout.finishLoadMore()
            }
        };

        mPageSize?.loadPage(true)
        binding.srlRefreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                if (mPageSize?.isLoading() == false) {
                    mPageSize?.loadPage(true)
                }
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (mPageSize?.isLoading() == false) {
                    mPageSize?.loadPage(false)
                }
            }
        })
    }


    private fun initView1() {
        // 1. 创建PageUi，指定UI组件
        val pageUi = PageUi<String>(
            scope = lifecycleScope,
            refreshLayout = binding.srlRefreshLayout,
            adapter = tiXingAdapter
        )

        // 2. 创建Pager，定义分页配置，指定获取数据的方法，设置监听器
        val pager = Pager(
            pageConfig = PageConfig(initIndex = 3),
            request = { page, size ->
                requestList(page = page, pageSize = size)
            })
            .apply {
                // 设置是否没有更多数据的状态监听器
                setNoMoreStateListener(object : PageState.NoMoreStateListener {
                    override fun noMoreState(noMoreState: Boolean) {
                        Log.e(TAG, "noMoreState = $noMoreState")
                    }
                })
                // 添加加载状态监听器
                addLoadStateListener(object : PageState.LoadStateListener {
                    override fun updateState(loadState: LoadState) {
                        when (loadState) {
                            is LoadState.NotLoading -> {
                                hideLoading()
                                showToast("加载完成")
                            }
                            is LoadState.Loading -> {
                                showLoading("加载中")
                            }
                            is LoadState.Error -> {
                                hideLoading()
                                showToast("加载失败，${loadState.error.message}")
                            }
                        }
                    }
                })
            }

        // 3. 创建PageHelper，将pageUi和pager联系起来
        pageHelper = PageHelper<String>(pageUi = pageUi, pager = pager)

        // 4. 通过代码进行刷新操作
        pageHelper.refresh()
    }

    private fun showToast(s: String) {
        Toast.makeText(this@MainActivity, s, Toast.LENGTH_SHORT).show()
    }

    private fun hideLoading() {
        progressDialog?.dismiss()
    }

    /**
     * 圆圈加载进度的 dialog
     */
    private fun showLoading(s: String) {
        progressDialog = ProgressDialog(this)
        progressDialog?.setIcon(R.mipmap.sym_def_app_icon)
        progressDialog?.setTitle("加载dialog")
        progressDialog?.setMessage("加载中...")
        progressDialog?.setIndeterminate(true) // 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
        progressDialog?.setCancelable(false) //点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
        progressDialog?.show()
    }

    fun requestList(page: Int, pageSize: Int): MutableList<String> {
        if (page > 10) {
            return mutableListOf()
        }
        var mList = mutableListOf<String>()
        for (i in 0..pageSize) {
            mList.add("这是数据 page$page size$pageSize ${(page - 1) * pageSize + i}")
        }
        return mList
    }
}